package com.vast.admin.service.impl;

import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSONUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.vast.admin.api.CietacApi;
import com.vast.admin.api.cietac.entity.CietacBackResultId;
import com.vast.admin.api.cietac.entity.CreateProject;
import com.vast.admin.entity.ArbitrationProject;
import com.vast.admin.entity.bo.ArbitrationProjectAddBo;
import com.vast.admin.entity.bo.ArbitrationProjectEditBo;
import com.vast.admin.entity.bo.ArbitrationProjectQueryBo;
import com.vast.admin.entity.vo.ArbitrationProjectVo;
import com.vast.admin.mapper.ArbitrationProjectMapper;
import com.vast.admin.service.IArbitrationProjectService;
import com.vast.common.constant.MessageCode;
import com.vast.common.core.domain.Result;
import com.vast.common.core.domain.entity.SysRole;
import com.vast.common.core.domain.entity.SysUser;
import com.vast.system.exception.BusinessException;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
import java.util.stream.Collectors;

/**
 * 仲裁项目Service业务层处理
 *
 * @author ruoyi
 * @date 2021-05-10
 */
@Service
public class ArbitrationProjectServiceImpl extends ServiceImpl<ArbitrationProjectMapper, ArbitrationProject> implements IArbitrationProjectService {

    @Autowired
    private CietacApi cietacApi;

    @Override
    public ArbitrationProjectVo queryById(Long id) {
        ArbitrationProject db = this.baseMapper.selectById(id);
        ArbitrationProjectVo arbitrationProjectVo = new ArbitrationProjectVo();
        BeanUtils.copyProperties(db, arbitrationProjectVo);
        return arbitrationProjectVo;
    }

    @Override
    public List<ArbitrationProjectVo> queryList(ArbitrationProjectQueryBo bo, SysUser manager) {
        LambdaQueryWrapper<ArbitrationProject> lqw = Wrappers.lambdaQuery();
        lqw.eq(bo.getCompanyId() != null, ArbitrationProject::getCompanyId, bo.getCompanyId());
        lqw.eq(bo.getType() != null, ArbitrationProject::getType, bo.getType());
        lqw.eq(bo.getProjectId() != null, ArbitrationProject::getProjectId, bo.getProjectId());
        lqw.like(StrUtil.isNotBlank(bo.getName()), ArbitrationProject::getName, bo.getName());
        lqw.eq(bo.getValid() != null, ArbitrationProject::getValid, bo.getValid());
        List<SysRole> roles = manager.getRoles();
        boolean isAdmin = false;
        for (SysRole role : roles) {
            if (role.getRoleKey().equals("admin")) {
                isAdmin = true;
                break;
            }
        }
        if (!isAdmin) {
            lqw.eq(ArbitrationProject::getCreateBy, manager.getUserId());
        }
        return entity2Vo(this.list(lqw));
    }

    /**
     * 实体类转化成视图对象
     *
     * @param collection 实体类集合
     * @return
     */
    private List<ArbitrationProjectVo> entity2Vo(Collection<ArbitrationProject> collection) {
        List<ArbitrationProjectVo> voList = collection.stream()
                .map(any -> {
                    ArbitrationProjectVo arbitrationProjectVo = new ArbitrationProjectVo();
                    BeanUtils.copyProperties(any, arbitrationProjectVo);
                    return arbitrationProjectVo;
                })
                .collect(Collectors.toList());
//        if (collection instanceof Page) {
//            Page<ArbitrationProject> page = (Page<ArbitrationProject>)collection;
//            Page<ArbitrationProjectVo> pageVo = new Page<>();
//            BeanUtil.copyProperties(page,pageVo);
//            pageVo.setRecords(voList);
//            voList = pageVo;
//        }
        return voList;
    }

    @Override
    public Boolean insertByAddBo(String user, ArbitrationProjectAddBo bo) {
        CreateProject createProject = new CreateProject();
        createProject.setName(bo.getName());
        createProject.setAttachment(bo.getAttachment());
        createProject.setAmount_scope_year(bo.getAmount_scope_year());
        createProject.setIntro(bo.getIntro());
        createProject.setAmount_scope_single(bo.getAmount_scope_single());
        createProject.setCase_date_unit(bo.getCase_date_unit());
        createProject.setCase_number(bo.getCase_number());
        Result<CietacBackResultId> result = cietacApi.createProject(user,createProject);
        if(result.getCode() == 0){
            ArbitrationProject add = new ArbitrationProject();
            BeanUtils.copyProperties(bo, add);
            add.setProjectId(result.getData().getId());
            validEntityBeforeSave(add);
            return this.save(add);
        }else{
            throw new BusinessException(MessageCode.SYSTEM_ERROR, JSONUtil.toJsonStr(result));
        }
    }

    @Override
    public Boolean updateByEditBo(ArbitrationProjectEditBo bo) {
        ArbitrationProject update = new ArbitrationProject();
        BeanUtils.copyProperties(bo, update);
        validEntityBeforeSave(update);
        return this.updateById(update);
    }

    /**
     * 保存前的数据校验
     *
     * @param entity 实体类数据
     */
    private void validEntityBeforeSave(ArbitrationProject entity) {
        //TODO 做一些数据校验,如唯一约束
    }

    @Override
    public Boolean deleteWithValidByIds(Collection<Long> ids, Boolean isValid) {
        if (isValid) {
            //TODO 做一些业务上的校验,判断是否需要校验
        }
        return this.removeByIds(ids);
    }

    @Override
    public List<ArbitrationProject> getList(SysUser manager) {
        LambdaQueryWrapper<ArbitrationProject> lqw = Wrappers.lambdaQuery();
        lqw.eq(ArbitrationProject::getStatus, "40");
        List<SysRole> roles = manager.getRoles();
        boolean isAdmin = false;
        for (SysRole role : roles) {
            if (role.getRoleKey().equals("admin")) {
                isAdmin = true;
                break;
            }
        }
        if (!isAdmin) {
            lqw.eq(ArbitrationProject::getCreateBy, manager.getUserId());
        }
        return this.list(lqw);
    }


	/**
	 * 同步案件状态
	 */
	@Override
	@Transactional(rollbackFor = Exception.class)
	public void syncStatus() {
		QueryWrapper<ArbitrationProject> arbitrationProjectQueryWrapper = new QueryWrapper<>();
		//案件状态 12 已完成 13 撤案 14 取消立案
		arbitrationProjectQueryWrapper.notIn(ArbitrationProject.COL_STATUS, "12", "13", "14");
		List<ArbitrationProject> arbitrationProjects = super.list(arbitrationProjectQueryWrapper);
		if (arbitrationProjects != null && !arbitrationProjects.isEmpty()) {
			List<Long> projectIds = new ArrayList<>(arbitrationProjects.size());
			arbitrationProjects.forEach(arbitrationProject -> projectIds.add(arbitrationProject.getProjectId()));
			Result<List<ArbitrationProject>> projectStatusResult = cietacApi.projectStatus(projectIds);
			if (projectStatusResult.getCode() == 0) {
				for (ArbitrationProject arbitrationProject : projectStatusResult.getData()) {
					UpdateWrapper<ArbitrationProject> arbitrationProjectUpdateWrapper = new UpdateWrapper<>();
					arbitrationProjectUpdateWrapper.set(ArbitrationProject.COL_STATUS, arbitrationProject.getStatus())
						.eq(ArbitrationProject.COL_PROJECT_ID, arbitrationProject.getProjectId());
					super.update(arbitrationProjectUpdateWrapper);
				}
			} else {
				log.error("案件状态同步失败");
			}
		}
	}

}




